/*
 * Copyright © Yan Zhenjie. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yanzhenjie.andserver.sample.handler.anjian;

import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.RequestMethod;
import com.yanzhenjie.andserver.annotation.RequestMapping;

import org.apache.httpcore.HttpEntity;
import org.apache.httpcore.HttpException;
import org.apache.httpcore.HttpRequest;
import org.apache.httpcore.HttpResponse;
import org.apache.httpcore.RequestLine;
import org.apache.httpcore.entity.BasicHttpEntity;
import org.apache.httpcore.entity.StringEntity;
import org.apache.httpcore.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.Proxy;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * <p>Returns a file.</p>
 * Created by Yan Zhenjie on 2016/7/1.
 */
public class ProxyHandler implements RequestHandler {

    private String[] responseInteceptorNames = new String[]{
        "Date",
        "Content-Length",
        "Transfer-Encoding"
    };

    protected boolean shouldBeFiltered(String name){
        boolean b = false;
        for (int i = 0; i < responseInteceptorNames.length; i++){
            if(name.equals(responseInteceptorNames[i])){
                b = true;
                break;
            }
        }
        return b;
    }

    @RequestMapping(method = {RequestMethod.GET})
    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        RequestLine requestLine = request.getRequestLine();

        OkHttpClient client = new OkHttpClient().newBuilder().proxy(Proxy.NO_PROXY).build();
        Request req = new Request.Builder().url(requestLine.getUri()).build();
        Response res = client.newCall(req).execute();

        String body = res.body().string();
        body = resolve(body);
        try {
            JSONObject json = new JSONObject(body);
            resolve(json);
            body = json.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        HttpEntity httpEntity = new StringEntity(body,"UTF-8");

        /*BasicHttpEntity httpEntity = new BasicHttpEntity();
        httpEntity.setContent(res.body().byteStream());*/
//        httpEntity.setContentLength(res.body().contentLength());
        Headers headers = res.headers();
        java.util.Iterator<String> it = headers.names().iterator();
        while(it.hasNext()){
            String name = it.next();
            if(shouldBeFiltered(name)){
                continue;
            }
            response.addHeader(name, res.header(name));
        }
        response.setStatusCode(res.code());
        response.setEntity(httpEntity);
    }

    protected String resolve(String data){ return data; }

    protected void resolve(JSONObject json){}

}
